﻿Imports DAL
Imports System.Data.SqlClient
Public Class frmSearchPO
    Public strPOs As String
    Private intSupplier As Integer
    Private IntItem As Integer
    Private intColor As Integer
    Private intPackSizeID As Integer
    Public SearchType As DGeneral.DocTypes

    Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
        Try
            txtPromoterCode.Text = ""
            txtPromoterName.Text = ""
            txtItemCode.Text = ""
            txtItemName.Text = ""
            txtCLRNAME.Text = ""
            txtPo.Text = ""
            txtCLRCODE.Text = ""
            cmbPAck.SelectedIndex = -1
            strPOs = String.Empty

            intSupplier = 0
            IntItem = 0
            intColor = 0
            intPackSizeID = 0
            dgItems.AllowUserToAddRows = False
            dgItems.Rows.Clear()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub frmSearchPO_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        btnClear_Click(Nothing, Nothing)
        With dgItems
            .Columns(1).HeaderText = "SELECT"
            If SearchType = DGeneral.DocTypes.PURCHASE_GRN Then
                lblID.Text = "GRN NO"
                .Columns(2).HeaderText = "GRN NO"
                .Columns(4).HeaderText = "GRN DATE"
                BTNok.Text = "GENERATE INVOICE"
            ElseIf SearchType = DGeneral.DocTypes.PURCHASE_INVOICE Then
                lblID.Text = "INVOICE NO"
                .Columns(2).HeaderText = "INVOICE NO"
                .Columns(4).HeaderText = "INVOICE DATE"
                BTNok.Text = "GENERATE RETURN INVOICE"
                lblGRN.Visible = True
                txtGRN.Visible = True
                txtSuplierInvoice.Visible = True
                lblSuplrInvoice.Visible = True
            End If
        End With
        subPriUpdatePack()
    End Sub

    Private Sub cmbPack_GotFocus(sender As Object, e As System.EventArgs) Handles cmbPAck.GotFocus
        sender.DroppedDown = True
    End Sub
    Private Sub cmbPack_SelectionChangeCommitted(sender As Object, e As System.EventArgs) Handles cmbPAck.SelectionChangeCommitted

        intPackSizeID = cmbPAck.SelectedValue
        '  SubPriGetPrice()
    End Sub

    
    Private Sub txtPo_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtPo.KeyDown
        If BCommon.ValidateText(txtPo.Text, e.KeyCode, "NUM", False) = False Then
            e.SuppressKeyPress = True
        End If
    End Sub


    Private Sub BtnCancel_Click(sender As System.Object, e As System.EventArgs) Handles BtnCancel.Click
        strPOs = String.Empty
        Me.Close()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Try
            Dim strWhereClause As String = String.Empty
            'strWhereClause = strWhereClause & " AND P.PurchaseType = " 
            If SearchType = DGeneral.DocTypes.PURCHASE_GRN Then 'CONVERTED GRN SHOULD Not be searched again
                strWhereClause = strWhereClause & "  AND BILLED = 0 "
            ElseIf SearchType = DGeneral.DocTypes.PURCHASE_INVOICE Then 'CONVERTED GRN SHOULD Not be searched again
                strWhereClause = strWhereClause & "   AND QTY > RetQty "
            Else

                strWhereClause = strWhereClause & "   AND QTY > ReceivedQty "
            End If
            If intSupplier > 0 Then
                strWhereClause = " AND  P.PromoterID = " & intSupplier.ToString()
                'Else //CP@09.OCT.2013, Remove compulsion of Suppliers
                '    MessageBox.Show(" Please select Supplier.")
                '    Exit Sub
            End If

            If IntItem > 0 Then
                strWhereClause = strWhereClause & "  AND D.ItemID = " & IntItem.ToString()
            End If

            If intColor > 0 Then
                strWhereClause = strWhereClause & " AND  D.CLRCode = " & intColor.ToString()
            End If
            If intPackSizeID > 0 Then
                strWhereClause = strWhereClause & "  AND D.PackSizeID = " & intPackSizeID.ToString()
            End If
            If txtPo.Text.Trim <> String.Empty Then
                strWhereClause = strWhereClause & " AND  P.SeqPurchaseID = " & txtPo.Text.Trim()
            End If

            If chkDate.CheckState = CheckState.Checked Then
                strWhereClause = strWhereClause & "  AND P.PurchaseDate  BETWEEN '" & Format(dtpFrom.Value, "MM/dd/yyyy") & " ' AND  '" & Format(DtpTO.Value, "MM/dd/yyyy") & "' "
            End If
            If SearchType = DGeneral.DocTypes.PURCHASE_GRN Then

            If txtSuplierInvoice.Text.Trim <> String.Empty Then
                strWhereClause = strWhereClause & "  AND P.SupplierDC  = " & txtSuplierInvoice.Text.Trim & "  "
            End If

                If txtGRN.Text.Trim <> String.Empty Then
                    strWhereClause = strWhereClause & "  AND P.PO_GRNID  = (SELECT PurchaseID from TPurchase WHERE SeqPurchaseID=" & txtGRN.Text.Trim & " ) "
                End If
            End If

            If strWhereClause = String.Empty Then
                strWhereClause = strWhereClause & "  AND P.PurchaseDate  = '" & Format(Now(), "MM/dd/yyyy") & " ' "
            End If


            If strWhereClause <> String.Empty Then

                Dim strSearchQuery As String
                strSearchQuery = "SELECT  DISTINCT P.PurchaseID, 0 AS SelectPO,SeqPurchaseID AS PONumber,S.SupplierName,PurchaseDate AS PO_DATE,P.PromoterID FROM tPurchase P INNER JOIN tPurchaseDet D ON(P.PurchaseID=D.PurchaseID) LEFT OUTER JOIN SUPPLIER S ON (S.ID=P.PromoterID)  WHERE PurchaseType = " & System.Convert.ToInt16(SearchType).ToString() & strWhereClause


                subPriFillList(strSearchQuery)
            Else
                MessageBox.Show(" Please select search criteria")
            End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub subPriFillList(ByVal strQuery As String)
        Dim ItemReader As SqlDataReader = DbHelper.ExecuteDataReader(strQuery)

        With Me.dgItems
            If ItemReader.IsClosed Then Exit Sub
            Dim intCount As Integer = 0
            .Columns(0).Visible = False
            .Columns(0).Width = 0
            .Columns("SUPPLIERID").Width = 0    '' Promoter ID
            .Columns("SUPPLIERID").Visible = 0
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .AllowUserToResizeRows = False
            .Rows.Clear()
            While ItemReader.Read()
                .RowCount += 1
                For intColcount As Integer = 0 To ItemReader.FieldCount - 1
                    .Item(intColcount, intCount).Value = ItemReader(intColcount)
                Next
                intCount += 1
            End While

        End With
        ItemReader.Close()
        'Dim dtbPo As DataTable = DbHelper.ExecuteDataTable(strQuery)
        'If Not IsNothing(dtbPo) Then
        '    With dgItems

        '        .DataSource = dtbPo
        '        .Columns(0).Visible = False
        '        Dim Column1CHEC As New DataGridViewCheckBoxColumn
        '        .Columns(0) = Column1CHEC
        '        'Column1CHEC.Name = "SelectPO"
        '        'Column1CHEC.HeaderText = "SelectPO"
        '        '.Columns.Insert(1, Column1CHEC)
        '        .RowHeadersVisible = False
        '        .SelectionMode = DataGridViewSelectionMode.FullRowSelect
        '        For intCols As Int16 = 0 To .Columns.Count - 1
        '            .Columns(intCols).ReadOnly = True
        '        Next
        '        .Columns(1).ReadOnly = False
        '    End With

        'End If

    End Sub

    Private Sub BTNok_Click(sender As System.Object, e As System.EventArgs) Handles BTNok.Click
        Try
            strPOs = String.Empty
            Dim intSupplier As Int16 = 0


            For intcnt As Int16 = 0 To dgItems.Rows.Count - 1
                If dgItems.Item(1, intcnt).Value = True Then

                    If SearchType = DGeneral.DocTypes.PURCHASE_ORDER Then
                        If intSupplier = 0 Then
                            intSupplier = dgItems.Item(5, intcnt).Value.ToString()
                        ElseIf (intSupplier <> dgItems.Item(5, intcnt).Value.ToString()) Then
                            MessageBox.Show("Multiplse Suppliers are selected cant generate GRN.")
                            Exit Sub
                        End If
                    ElseIf SearchType = DGeneral.DocTypes.PURCHASE_GRN Then
                        If strPOs <> String.Empty Then
                            MessageBox.Show("Select only one GRN to convert as Invoice.")
                            Exit Sub
                        End If
                    End If
                    strPOs = strPOs & IIf(strPOs = String.Empty, "", ",") & dgItems.Item(0, intcnt).Value.ToString
                End If
            Next
            

            'For Each Rw As DataGridViewRow In dgItems.Rows
            '    If Rw SelectPO Then
            '        strPOs = IIf(strPOs = String.Empty, "", ",") & dgItems.Item(0, intcnt).Value.ToString
            'Next

            If strPOs = String.Empty Then
                MessageBox.Show("No Record selected, Click Cancel to exit.")
            Else
                Me.Close()
            End If
        Catch ex As Exception

        End Try
    End Sub

#Region "COMMON SEARCH"


    Private Sub txtPartyCode_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtItemCode.Enter, txtItemName.Enter, txtPromoterCode.Enter, txtPromoterName.Enter, txtCLRCODE.Enter, txtCLRNAME.Enter, txtPromoterName.Enter

        If sender.Text.ToString = String.Empty Then
            sender.BackColor = Color.LightBlue
            SearchParty_Promoter_Site(sender)
        End If
    End Sub
    Private Sub txtCLRCODE_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtItemCode.KeyDown, txtItemName.KeyDown, txtPromoterCode.KeyDown, txtPromoterName.KeyDown, txtCLRCODE.KeyDown, txtCLRNAME.KeyDown, txtPromoterName.KeyDown
        If (cmbPAck.Name <> sender.Name) AndAlso e.KeyCode = Keys.Back Then
            e.SuppressKeyPress = True
            SearchParty_Promoter_Site(sender)
        ElseIf e.KeyCode = Keys.Enter Then
            SendKeys.Send("{Tab}")
        ElseIf e.KeyCode = Keys.Tab Then
        ElseIf (cmbPAck.Name <> sender.Name) Then
            e.SuppressKeyPress = True
        End If
    End Sub

    Private Function GetSearchQuery(ByVal Sender As Object, ByRef strSearchString As String) As String
        Select Case Sender.Name
            Case txtPromoterCode.Name, txtPromoterName.Name
                strSearchString = "SUPPLIER "
                Return "SELECT P.ID ,P.SupplierCode AS CODE,P.SupplierName AS NAME ,P.Address FROM Supplier P WHERE ISDELETED=0"
                'Case txtPromoterCode.Name, txtPromoterName.Name
                '    strSearchString = "PROMOTER "
                '    Return "SELECT P.Id,P.PromoterCode AS CODE ,P.PromoterName AS NAME FROM [NGSPaintsDB].[dbo].promoter P WHERE P.IsDeleted=0"
                'Case txtSiteCode.Name, txtSiteName.Name
                '    strSearchString = "SITE "
                '    Return " SELECT [Id],[SiteCode]AS CODE ,[SiteName] AS NAME,ISNULL(PriceListId,0) AS PriceListId  FROM [NGSPaintsDB].[dbo].[Site] WHERE [IsDeleted]=0" & IIf(intParty > 0, " AND PartyID=" & intParty.ToString, "")
                'Case txtPrice.Name 'PRICE LIST
                'CmbPriceList.Focus()    Return "SELECT [ID],[PRICELISTCODE]AS CODE ,[PRICELISTNAME] AS NAME  FROM [NGSPAINTSDB].[DBO].[PRICELIST] WHERE [ISDELETED]=0"
            Case txtItemCode.Name, txtItemName.Name
                strSearchString = "PRODUCT "
                Return "SELECT P.[Id] AS ItemID,P.[ProductCode] AS Code,P.[ProductName] AS Name, P.TAXID,P.IsColor FROM [NGSPaintsDB].[dbo].Product P WHERE ISDeleted=0 ORDER BY NAME"
            Case txtCLRCODE.Name, txtCLRNAME.Name

                strSearchString = "COLOR "
                Return "SELECT DISTINCT C.[Id],C.[ColorCode] AS CODE ,C.[ColorDescription] AS NAME  FROM [Color] AS C  INNER JOIN  PackingUpdateDetail  D ON (D.ColorID=C.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE C.[IsDeleted]=0  AND C.ID > 0   AND D.GodownId > 0 "
            Case cmbPAck.Name

                strSearchString = "PACK "
                Return "SELECT DISTINCT S.ID ,S.PackSize + ' ' + S.PackingDescription AS CODE FROM  PackingSize S INNER JOIN PackingUpdateDetail  D ON (D.PackSizeID=S.ID) INNER JOIN  PackingUpdate P ON(P.ID=D.PackingUpdateId) WHERE S.[IsDeleted]=0  AND D.GodownId > 0 "
            Case Else
                Return ""
        End Select
    End Function

    Private Sub SearchParty_Promoter_Site(ByVal sender As Object)
        Try
            Dim TxtSearch As TextBox = sender

            Dim frmListProducts As New frmProducts
            With frmListProducts

                .Left = Me.Right - Me.Width - 5
                .Top = Me.Top + grpTop.Size.Height
                .intSelectedItem = 0
                Dim strSearch As String = ""
                .StrSearchQuery = GetSearchQuery(TxtSearch, strSearch)
                If .StrSearchQuery = String.Empty Then Exit Sub
                .strSearchByCode = strSearch & IIf(sender.Name.ToString.ToUpper.Contains("CODE"), "CODE:", "NAME:")

                .txtProduct.Text = TxtSearch.Text

                .ShowDialog(Me)
                'intSelectedProduct = frmListProducts.intSelectedItem
            End With


            If frmListProducts.intSelectedItem > 0 Then
                With frmListProducts.fgProducts
                    If .CurrentRow.Index >= 0 Then
                        Select Case TxtSearch.Name
                            'Case txtPartyCode.Name, txtPartyName.Name
                            '    intParty = .Item(0, .CurrentRow.Index).Value
                            '    txtPartyCode.Text = .Item(1, .CurrentRow.Index).Value
                            '    txtPartyName.Text = .Item(2, .CurrentRow.Index).Value
                            '    ' Dim intLocPriceListID As Integer = .Item(4, .CurrentRow.Index).Value
                            '    'If intLocPriceListID > 0 Then
                            '    '    CmbPriceList.SelectedValue = intLocPriceListID
                            '    '    cmbPack_SelectionChangeCommitted(Nothing, Nothing)
                            '    'End If
                            '    rTxtAddress.Text = .Item(3, .CurrentRow.Index).Value
                            '    'If PurchaseType = DGeneral.DocTypes.QUOTATION Then
                            '    '    rTxtAddress.Text = funpriGetTermsAndConditions()
                            '    'Else
                            '    '    rTxtAddress.Text = .Item(3, .CurrentRow.Index).Value
                            '    'End If
                            '    lblChallanType.Text = .Item(5, .CurrentRow.Index).Value
                            '    sender.BackColor = Color.White
                            '    SendKeys.Send("{TAB}")
                            Case txtPromoterCode.Name, txtPromoterName.Name
                                intSupplier = .Item(0, .CurrentRow.Index).Value
                                txtPromoterCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtPromoterName.Text = .Item(2, .CurrentRow.Index).Value
                                sender.BackColor = Color.White
                                SendKeys.Send("{TAB}")
                                'Case txtSiteCode.Name, txtSiteName.Name
                                '    intSite = .Item(0, .CurrentRow.Index).Value
                                '    txtSiteCode.Text = .Item(1, .CurrentRow.Index).Value
                                '    txtSiteName.Text = .Item(2, .CurrentRow.Index).Value
                                '    If PurchaseType = DGeneral.DocTypes.PURCHASE_ORDER Then
                                '        rTxtAddress.Text = GetSiteAddress(intSite)
                                '    End If
                                '    'Dim intLocPriceListID As Integer = .Item(3, .CurrentRow.Index).Value
                                '    'If intLocPriceListID > 0 Then
                                '    '    CmbPriceList.SelectedValue = intLocPriceListID
                                '    '    cmbPack_SelectionChangeCommitted(Nothing, Nothing)
                                '    'End If
                                '    sender.BackColor = Color.White
                                '    SendKeys.Send("{TAB}")
                            Case txtItemCode.Name, txtItemName.Name
                                '  subPriClearItemDtls()
                                IntItem = .Item(0, .CurrentRow.Index).Value
                                txtItemCode.Text = .Item(1, .CurrentRow.Index).Value
                                txtItemName.Text = .Item(2, .CurrentRow.Index).Value
                                '   intTaxID = .Item(3, .CurrentRow.Index).Value
                                SendKeys.Send("{TAB}")
                            Case txtCLRCODE.Name, txtCLRNAME.Name
                                intColor = .Item(0, .CurrentRow.Index).Value
                                txtCLRCODE.Text = .Item(1, .CurrentRow.Index).Value
                                txtCLRNAME.Text = .Item(2, .CurrentRow.Index).Value
                                '   subPriUpdatePack()
                                sender.BackColor = Color.White
                                SendKeys.Send("{TAB}")
                                'cmbPack.DroppedDown = True

                            Case Else
                                Exit Sub
                        End Select
                    End If
                End With
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.ToString, Me.ProductName, Me.Name, "showProductList")
        Finally
            sender.BackColor = Color.White
        End Try
    End Sub
    Private Sub subPriUpdatePack()

        Dim strPackQury As String = GetSearchQuery(cmbPAck, "")
        Dim dtbpack As DataTable = DbHelper.ExecuteDataTable(strPackQury)
        Dim pk(0) As System.Data.DataColumn
        pk(0) = dtbpack.Columns(0)
        dtbpack.PrimaryKey = pk
        cmbPAck.DataSource = dtbpack
        cmbPAck.ValueMember = "ID"
        cmbPAck.DisplayMember = "CODE"
        cmbPAck.SelectedIndex = -1

    End Sub
#End Region

    Private Sub chkSelectAll_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkSelectAll.CheckedChanged
        Dim CurrentStatus As Boolean = chkSelectAll.CheckState
        For intcnt As Int16 = 0 To dgItems.Rows.Count - 1
            dgItems.Item(1, intcnt).Value = CurrentStatus
        Next
    End Sub
    Private Sub txtPo_GotFocus(sender As Object, e As System.EventArgs) Handles txtPo.GotFocus, txtGRN.GotFocus, txtSuplierInvoice.GotFocus
        Dim txtobject As TextBox = sender
        txtobject.BackColor = Color.LightBlue
    End Sub

    Private Sub txtPo_LostFocus(sender As Object, e As System.EventArgs) Handles txtPo.LostFocus, txtGRN.LostFocus, txtSuplierInvoice.LostFocus
        Dim txtobject As TextBox = sender
        txtobject.BackColor = Color.White
    End Sub
End Class
